/*
 * @Description: 全宗列表导航
 * @Author: Rfan
 * @Date: 2022-02-09 17:58:25
 * @LastEditTime: 2023-02-27 09:25:03
 */

import { Key, useEffect, useState } from 'react';
import { Tree } from 'antd';
import classNames from 'classnames/bind';
import { observer } from 'mobx-react-lite';
import { fetchFondsListByUnitId } from '@/api/fonds';

import styles from './index.module.scss';
import { appState } from '@/store/mobx';

const cx = classNames.bind(styles);

const FondsNav = ({ onChange }: any) => {
  // 全宗列表
  const [fondList, setFondList] = useState([]);
  // 选中的节点key，TODO：有子节点是需要测试
  const [selectKey, setSelectKey] = useState([]);

  // 加载时获取单位列表，获取成功后默认选中第一条并把第一条返回出去
  useEffect(() => {
    const { unitId } = appState;
    if (unitId) {
      fetchFondsListByUnitId(unitId).then((res) => {
        const _fondList = res.data;
        setFondList(_fondList);
        setSelectKey([_fondList[0]?.id]);
        if (_fondList.length > 0) {
          onChange(_fondList[0]?.id, _fondList[0]);
        } else {
          onChange(0, {});
        }
      });
    }
  }, [appState.unitId]);

  // Tree组件设置为受控组件，选中节点时设置选中的key并将选中的内容返回出去
  const onSelect = (selectedKeys: Key[], info: any) => {
    if (selectedKeys.length > 0) {
      setSelectKey(selectedKeys);
      onChange(selectedKeys[0], info.selectedNodes[0]);
    }
  };

  return (
    <div className={cx('container')}>
      <h6 className={cx('fond-header')}>全宗列表</h6>
      <div className="fond-navs">
        <Tree
          onSelect={onSelect}
          treeData={fondList}
          fieldNames={{
            title: 'fondName',
            key: 'id'
          }}
          selectedKeys={selectKey}
        />
      </div>
    </div>
  );
};

export default observer(FondsNav);
